import * as echarts from '../../ec-canvas/echarts';
import {
  scores,
  finishdayofpressure,
  daysofpressure,
} from '../../api/index.js';

let barec = null;
Page({
  data: {
    url: wx.getStorageSync('url'),
    isPlaying: true,
    ec: {
      onInit: function (canvas, width, height) {
        barec = echarts.init(canvas, null, {
          width: width,
          height: height
        }, {
          renderer: 'svg'
        });
        canvas.setChart(barec);
        return barec;
      }
    },
    overallTime: 0,
    time: '00:00',
    currentTime: 0,
    sliderValue: 0,
    sliderMax: 100,
    isMovingSlider: false,
    entity: {},
    //勋章状态
    medalStatus: false,
    //勋章的弹出图片
    medalImage: '',
    //推荐计划的id
    newPlanId: '',
    //推荐状态
    newPlanStatus: false,
    //推荐的弹出图片
    newPlanImage: '',
    //完成状态
    finishStatus: false,
    //完成的弹出图片
    finishiImage: '',
    //弹出徽章
    showModalMedal: false,
    //弹出推荐计划
    showModalNewPlan: false,
    //弹出整个计划完成
    showModalFinishPlan: false,
    //播放完就弹出
    showModalFinishDay: false,
    //播放完弹出的图片路径
    finishDayImage: '../../images/gl.png',
    //当前任务第几天
    currentDay: '',
  },

  onReady(e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    this.getScores()
  },

  onShow: function (options) {
    /**
     * 生命周期函数--监听页面展示
     * 1. 如果后台音乐正在播放，那么读取修改isplaying状态和进度状态，展示entity即可。
     * 2. 如果没有在播放，看一下entity有没有，没有就从存储里面读取。
     * 3. 如果有entity，那么和存储里面的对比一下，一样就继续播放，不一样就从头播放。
     */
    let entity = wx.getStorageSync('entity')
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    let orig_src = backgroundAudioManager.src;
    if (entity) {
      if (typeof (orig_src) == "undefined" || orig_src != entity.audio_src) {
        // 首次进入播放页面，或者更换了新的课程音频之后再次进入课程页面，那么刷新audio_src，从头播放
        this.clearAudioManagerHandler(backgroundAudioManager);
        console.log('playBackgroundAudio:', entity.audio_src)
        this.setData({
          entity: entity,
          isPlaying: true
        })
        this.setTimeUpdateHandler(backgroundAudioManager);
        wx.playBackgroundAudio({
          title: entity.title,
          dataUrl: entity.audio_src
        });
      } else {
        // orig_src和entity.audio_src相同的情况，则播放即可
        console.log(entity);
        this.setTimeUpdateHandler(backgroundAudioManager);
        this.setData({
          entity: entity,
          isPlaying: true
        });
        backgroundAudioManager.play();
      }
      backgroundAudioManager.onStop(() => {
        this.setData({
          isPlaying: false
        })
      })
    }
  },

  clearAudioManagerHandler(backgroundAudioManager) {
    backgroundAudioManager.onPlay(() => { });
    backgroundAudioManager.onStop(() => { })
    backgroundAudioManager.onSeeked(() => { });
    backgroundAudioManager.onTimeUpdate(() => { });
  },

  //监听音频播放事件
  setTimeUpdateHandler(backgroundAudioManager) {
    backgroundAudioManager.onTimeUpdate(() => {
      if (this.data.isMovingSlider) {
        return;
      }

      let second = parseInt(backgroundAudioManager.currentTime)
      let currentTime = backgroundAudioManager.currentTime
      let sliderValue = currentTime
      let sliderMax = parseInt(backgroundAudioManager.duration)
      let time = this.s_to_hs(second)
      let overallTime = this.s_to_hs(sliderMax)
      this.setData({
        time,
        currentTime,
        sliderValue,
        sliderMax,
        overallTime
      });
    });

    backgroundAudioManager.onEnded(() => {
      //音频放完，调用接口
      daysofpressure().then(res => {
        if (res.errcode == '00000') {
            this.setData({
              showModalFinishDay: true,
              currentDay: res.days.find(day => day.id === res.currentDayId).sequence
            })
          }
        }
      )

      let dx = {}
      finishdayofpressure(dx).then(res => {
        /*TODO: 重新做图片之后再放上去
        if (res.errcode == '00000') {
          if (res.finish == 1) {
            this.setData({
              finishStatus: true,
              finishImage: res.finishImage
            })
          }
        }*/
      })
    });

  },

  // 滑块拖动的时候禁止TimeUpdate
  handleTimeSliderDragStart(e) {
    console.log('handleTimeSliderDragStart');
    this.setData({
      isMovingSlider: true
    });
  },

  // 滑块拖动结束可以TimeUpdate
  handleTimeSliderDragEnd(e) {
    console.log('handleTimeSliderDragEnd');
    this.setData({
      isMovingSlider: false
    });
  },

  //滑块 调时间
  handleTimeSliderChange(e) {
    //当前的秒数
    let s = e.detail;
    console.log(s);
    this.setData({
      isMovingSlider: true
    });
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    backgroundAudioManager.seek(Math.round(s * 100) / 100)
    backgroundAudioManager.onSeeked(() => {
      this.setData({
        isMovingSlider: false
      });
    })
  },

  //播放按钮事件
  playAudio() {
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    if (this.data.isPlaying) {
      this.setData({
        isPlaying: false
      });
      backgroundAudioManager.pause();
    } else {
      this.setData({
        isPlaying: true
      })
      backgroundAudioManager.play();
    }
  },

  left15() {
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    var nextTime = this.data.currentTime - 15
    backgroundAudioManager.onTimeUpdate(() => {});
    backgroundAudioManager.seek(nextTime);
    this.setTimeUpdateHandler(backgroundAudioManager);
  },
  right15() {
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    var nextTime = this.data.currentTime + 15
    backgroundAudioManager.seek(nextTime)
    this.setTimeUpdateHandler(backgroundAudioManager);
  },

  onClickMedalHide() {
    this.setData({
      medalStatus: false,
      showModalMedal: false
    });
    if (this.data.finishStatus) {
      return this.setData({
        showModalFinishPlan: true
      })
    }
    if (this.data.newPlanStatus) {
      return this.setData({
        showModalNewPlan: true
      })
    }
  },

  onClickFinishHide() {
    this.setData({
      finishStatus: false,
      showModalFinishPlan: false
    });
    if (this.data.newPlanStatus) {
      return this.setData({
        showModalNewPlan: true
      })
    }
  },

  onClickNewPlanHide() {
    this.setData({
      newPlanStatus: false,
      showModalNewPlan: false
    });
  },

  handleAddPlan() {
    wx.navigateTo({
      url: '/pages/course-description/course-description?planId=' + this.data.newPlanId,
    })

  },
  handleGetMedal() {
    wx.navigateTo({
      url: '/pages/my-medal/my-medal'
    })
  },

  onClickFinishDayHide() {
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    this.setData({
      showModalFinishDay: false
    });
    if (this.data.medalStatus) {
      return this.setData({
        showModalMedal: true
      })
    }
    if (this.data.finishStatus) {
      return this.setData({
        showModalFinishPlan: true
      })
    }
    if (this.data.newPlanStatus) {
      return this.setData({
        showModalNewPlan: true
      })
    }
    this.clearAudioManagerHandler(backgroundAudioManager);
    wx.switchTab({
      url: '/pages/home/home'
    })


  },

  //这个是获取echarts的数据
  getScores() {
    scores().then(res => {
      let dates = []
      let scores = []
      if (res.errcode == '00000') {
        if (res.scores.length > 0) {
          let newary = res.scores.slice(0, 6)
          newary.reverse().forEach(item => {
            if (item.score == -1) {
              item.score = 0
            }
            let date = item.date.split('-')[2] + '日'
            dates.push(date)
            scores.push(item.score)
          })
        }

        setTimeout(() => {
          console.log('init the echarts')
          barec.setOption({
            title: {
              text: '压力指数',
              show: true,

              x: 'center',
              y: 'top',
              textAlign: 'left',
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985'
                }
              },
              // padding: [5, 10]
            },

            toolbox: {
              show: false,
              feature: {
                saveAsImage: {}
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: [{
              type: 'category',
              axisLabel: {
                textStyle: { //改变刻度字体样式
                  color: '#999999'
                },
              },
              axisLine: {
                lineStyle: {
                  color: '#cadbe8'
                } // x轴坐标轴颜色
              },

              data: dates
              // data: dates,
            }],
            yAxis: [{
              type: 'value',
              "axisLine": { //y轴
                "show": false
              },
              "axisTick": { //y轴刻度线
                "show": false
              },
              axisLabel: {
                textStyle: {
                  color: '#999999'
                }
              }
            },

            ],
            series: [{
              name: '压力指数',
              type: 'line',
              stack: '总量',
              areaStyle: {},
              data: scores,
              // data: scores,
              itemStyle: {
                color: '#5b83f4'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: '#c1d3fd'
                }, {
                  offset: 1,
                  color: '#f5f8ff'
                }])
              },
            }]
          })
        }, 1000)
      }
    })

  },
  backHome() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  //分享
  onShareAppMessage: function () {
    return {
      title: '我正在使用SMART睡眠训练计划，超有用！推荐给你',
      imageUrl: '../../images/98875.jpg'

    }
  },


  /**
   * 将秒转换为 分:秒
   * s int 秒数
   */
  s_to_hs(s) {
    //计算分钟
    //算法：将秒数除以60，然后下舍入，既得到分钟数
    var h;
    h = Math.floor(s / 60);
    //计算秒
    //算法：取得秒%60的余数，既得到秒数
    s = s % 60;
    //将变量转换为字符串
    h += '';
    s += '';
    //如果只有一位数，前面增加一个0
    h = (h.length == 1) ? '0' + h : h;
    s = (s.length == 1) ? '0' + s : s;
    return h + ':' + s;
  },
  getUrlDomain(url) {
    var domain = url.split('/'); //以“/”进行分割
    if (domain[2]) {
      domain = domain[2];
    } else {
      domain = ''; //如果url不正确就取空
    }
  },
  getUrlRelativePath(url) {
    var arrUrl = url.split("//");

    var start = arrUrl[1].indexOf("/");
    var relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符

    return relUrl;
  }
});